/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.common.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * ip 地址转换为 long
 *
 * @author 挺好的 2023年06月05日 8:29
 */
public final class IpToLongUtils {

    private IpToLongUtils () {
    }
    
    /**
     * ip 转换为Long类型
     *
     * @param ip
     *         ip地址
     *
     * @return long ip address
     */
    public static long toLong (String ip) {
        if (StringUtils.isEmpty(ip)) {
            return 0L;
        }
        String[] ipArray = StringUtils.split(ip, "\\.");
        return (Long.parseLong(ipArray[0]) << 24) + (Long.parseLong(ipArray[1]) << 16) + (Long.parseLong(
                ipArray[2]) << 8) + Long.parseLong(ipArray[3]);
    }

    /**
     * 把IP的long值转换成字符串
     *
     * @param ipLong
     *         IP的long值
     *
     * @return long值对应的字符串
     */
    public static String toIp (long ipLong) {
        StringBuilder ip = new StringBuilder();
        ip.append(ipLong >>> 24).append(".");
        ip.append((ipLong >>> 16) & 0xFF).append(".");
        ip.append((ipLong >>> 8) & 0xFF).append(".");
        ip.append(ipLong & 0xFF);
        return ip.toString();
    }
}
